package com.lty.util;

import com.lty.code.bean.Entity;
import com.lty.code.bean.FieldInfo;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.beetl.core.resource.StringTemplateResourceLoader;

import java.io.IOException;
import java.util.List;

/**
 *
 * @author lty
 */
public class CodeUtil {

    public static final String varEntity = "entity";
    public static final String varFieldInfoList = "fieldInfoList";

    public static Entity getEntity() {
        Entity entity = new Entity();
        entity.setEntityPackage("com.lty.model.entity");
        entity.setDaoPackage("com.lty.mapper");
        entity.setServicePackage("com.lty.service");
        entity.setServiceImplPackage("com.lty.service.impl");
        entity.setControllerPackage("com.lty.controller");
        entity.setAuthor("lty");
        entity.setClassName("Book");
        entity.setClassNameLowerCase("book");
        entity.setTableName("");
        entity.setDescription("书管理");
        entity.setPrimaryKeyType("String");
        return entity;
    }

    public static String getTemplateResult(Template template, Entity entity, List<FieldInfo> fieldInfoList) {
        template.binding(varEntity, entity);
        template.binding(varFieldInfoList, fieldInfoList);
        String result = template.render();
        return result;
    }

    public static Template getTemplate(String templateName) throws IOException {
        // 模板路径
        ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("/template/");

        Configuration cfg = Configuration.defaultConfiguration();
        GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
        return gt.getTemplate(templateName);
    }

    /**
     * 根据字符串获取模板
     * @param templateString
     * @return
     * @throws IOException
     */
    public static Template getTemplateByString(String templateString) throws IOException {
        StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
        Configuration cfg = Configuration.defaultConfiguration();
        GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
        return gt.getTemplate(templateString);
    }
}
